import base64
import pickle
import re
from django.conf import settings
from rest_framework import serializers
from goods.models import SKU
from users.models import User
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from celery_tasks.meiduofunc.tasks import send_email
# from django.core.mail import send_mail

class UserSerializer(serializers.ModelSerializer):
    """
    username,password,password2,mobile,sms_code,allow
    """
    password2 =  serializers.CharField(max_length=20,min_length=8,write_only=True)
    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('id','username','mobile','password','password2','sms_code','allow','token')
        extra_kwargs = {
            'password':{'max_length':20,'min_length':8,'write_only':True},
            'username':{'max_length':20,'min_length':5}
        }

    def validate(self, attrs):
        conn = get_redis_connection("sms_code")
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        reds_sms = conn.get('sms_code:%s'%mobile)
        if re.match(r'1[3-9]\d{9}',attrs['username']):
            if attrs['username'] != attrs['mobile']:
                raise serializers.ValidationError('用户名与手机号不一致')
        if not reds_sms:
            raise serializers.ValidationError('验证码已过期,请重新获取')
        if sms_code != reds_sms.decode():
            raise serializers.ValidationError('验证码不正确!')
        if attrs.get('password') != attrs.get('password2'):
            raise serializers.ValidationError('两次输入的密码不一致')
        allow = attrs.get('allow')
        if not allow:
            # return Response({'message':'请确认协议!'})
            raise serializers.ValidationError('请确认协议')
        mobile = attrs.get('mobile')
        b = re.match(r'1[3-9]\d{9}',mobile)
        if not b:
            # return Response({'message':'手机号格式不正确!'})
            raise serializers.ValidationError('手机号格式不正确')
        return attrs

    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create_user(**validated_data)
        # user.set_password(validated_data['password'])
        user.save()

        # return (user.id,user.username,user.mobile)
        # return { "id":user.id,"username":user.username,"mobile":user.mobile }

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token=token
        return user


class UserCenterSerializer(serializers.ModelSerializer):

    # token = serializers.CharField()

    class Meta:
        model = User
        fields = ('username','id','mobile','email','email_active')


class UseremailSerializer(serializers.Serializer):

    email = serializers.EmailField()

    def update(self, instance, validated_data):

        tjs = TJS(settings.SECRET_KEY,300)
        token = tjs.dumps({'username':instance.username}).decode()

        instance.email = validated_data['email']
        instance.save()

        send_email.delay(token,validated_data['email']) #启动异步任务需要加delay命令进行执行

        # verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
        # subject = "美多商城邮箱验证(何明昊版)"
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (validated_data['email'], verify_url, verify_url)
        #
        # send_mail(subject, '', settings.EMAIL_FROM, [validated_data['email']], html_message=html_message)


        return instance


class BrowseHistorySerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    def create(self, validated_data):

        user = self.context['request'].user
        sku_id = validated_data['sku_id']
        conn = get_redis_connection('history')
        pl = conn.pipeline()
        pl.lrem('history_%s'%user.id,0,sku_id)
        pl.lpush('history_%s'%user.id,sku_id)
        pl.ltrim('history_%s'%user.id,0,4)
        pl.execute()

        return validated_data


class SkuHistorySerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = '__all__'


class UpdatePassWordSerializer(serializers.Serializer):

    old_password = serializers.CharField(min_length=8,max_length=20,write_only=True)
    password = serializers.CharField(min_length=8,max_length=20,write_only=True)
    password2 = serializers.CharField(min_length=8,max_length=20,write_only=True)

    def validate(self, attrs):

        old_password = attrs['old_password']
        user = self.context['request'].user
        if not user.check_password(old_password):
            raise serializers.ValidationError({'message':'原始密码不正确'})
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError({'message':'两次密码输入不一致!'})

        return attrs

    def update(self, instance, validated_data):

        # old_password = validated_data['old_password']
        # ret = instance.check_password(old_password)
        # if not ret:
        #     raise serializers.ValidationError({'message':'原始密码错误!'})
        password = validated_data['password']

        instance.set_password(password)

        instance.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(instance)
        token = jwt_encode_handler(payload)
        instance.token = token

        return instance

class UpdateUserSerializer(serializers.ModelSerializer):

    # password = serializers.CharField(min_length=8,max_length=20,write_only=True)
    password2 = serializers.CharField(min_length=8,max_length=20,write_only=True)
    access_token = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('password2','access_token','password')
        extra_kwargs = {
            'password': {'max_length': 20, 'min_length': 8, 'write_only': True}
        }

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({'errmage':'两次密码不一致'})

        access_token = attrs['access_token']
        user_dict = pickle.loads(base64.b64decode(access_token))
        username = user_dict.get('username')
        mobile = user_dict.get('mobile')
        try:
            user = User.objects.get(username=username,mobile=mobile)
        except:
            raise serializers.ValidationError({'errmage':'用户不存在!'})

        return attrs

    def update(self, instance, validated_data):

        password = validated_data['password']

        instance.set_password(password)

        instance.save()

        return instance
